﻿using DB.EF;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using VOL.Entity.DomainModels;


//引入Microsoft.Extensions.Logging.Console
namespace EF.DB
{
    public class MysqlContext: DbContext
    {
        private static readonly ILoggerFactory _loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());

        public MysqlContext()
        {

        }

        public DbSet<operatelog> operatelogs { get; set; }
        public DbSet<qx_wxd_nr> qx_wxd_nrs { get; set; }
        public DbSet<qx_mx_peijian> qx_mx_peijians { get; set; }
        public DbSet<qx_mx_weixiu> qx_mx_weixius { get; set; }
        public DbSet<qx_peijian> qx_peijians { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(DbConnStr.connStr, ServerVersion.AutoDetect(DbConnStr.connStr), p => p.CommandTimeout(180));
            optionsBuilder.AddInterceptors(new DbCommandCustomInterceptor());
            optionsBuilder.UseLoggerFactory(_loggerFactory);
        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            // 配置逻辑删除的属性
            builder.Entity<qx_wxd_nr>().HasQueryFilter(e => e.IsDeleted == 0);
            builder.Entity<qx_peijian>().HasQueryFilter(e => e.IsDeleted == 0);
            builder.Entity<qx_car>().HasQueryFilter(e => e.IsDeleted == 0);


            builder.Entity<qx_peijian>().Property(e=>e.RowVersion).IsConcurrencyToken();
            builder.Entity<qx_wxd_nr>().Property(e => e.RowVersion).IsConcurrencyToken();
            builder.Entity<qx_mx_peijian>().Property(e => e.RowVersion).IsConcurrencyToken();
            builder.Entity<qx_mx_weixiu>().Property(e => e.RowVersion).IsConcurrencyToken();
            builder.Entity<operatelog>().Property(e => e.RowVersion).IsConcurrencyToken();
            builder.Entity<qx_car>().Property(e => e.RowVersion).IsConcurrencyToken();
            /*
             *  使用乐观锁之前得在mysql数据库中创建触发器
             *  触发器的作用是数据库每次更新时，都会在乐观锁字段创建或更新一个当前时间戳
             *  创建触发器 qx_peijian
                CREATE TRIGGER mytr_qx_peijian
                BEFORE UPDATE ON qx_peijian
                FOR EACH ROW
                BEGIN
                   SET NEW.RowVersion = NEW.RowVersion + 1;
                END;
                DELIMITER ;

             *  删除触发器
                DROP TRIGGER mytr_qx_peijian

             *  mysql查询所有触发器
                SELECT
                    TRIGGER_SCHEMA,
                    TRIGGER_NAME
                FROM
                    INFORMATION_SCHEMA.TRIGGERS;
             */



        }


    }
}
